package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @version v1.0
 * @author OldGj 2024/5/27
 * @apiNote 数据统计业务层相关实现类
 */
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateTimeList = new ArrayList<>();
        dateTimeList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateTimeList.add(begin);
        }
        // 创建一个存放一天营业额的集合
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateTimeList) {
            // 遍历每天的时间，从数据库中查询当天的营业额是多少
            // 营业额：当天订单状态为以完成的订单金额总量
            // 封装参数
            Map<String, Object> map = new HashMap();
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            // 查询得到一天的营业额
            Double amount = orderMapper.sumWithMap(map);
            amount = amount != null ? amount : 0;
            turnoverList.add(amount);
        }

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateTimeList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }


    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer> newUserList = new ArrayList<>(); //新增用户数
        List<Integer> totalUserList = new ArrayList<>(); //总用户数

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //新增用户数量 select count(id) from user where create_time > ? and create_time < ?
            Integer newUser = getUserCount(beginTime, endTime);
            //总用户数量 select count(id) from user where  create_time < ?
            Integer totalUser = getUserCount(null, endTime);

            newUserList.add(newUser);
            totalUserList.add(totalUser);
        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    /**
     * 根据时间区间统计用户数量
     * @param beginTime
     * @param endTime
     * @return
     */
    private Integer getUserCount(LocalDateTime beginTime, LocalDateTime endTime) {
        Map map = new HashMap();
        map.put("begin", beginTime);
        map.put("end", endTime);
        return userMapper.countByMap(map);
    }


    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        // 构造时间集合
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        // 订单总数
        Integer totalOrderCount = 0;
        // 有效订单数
        Integer validOrderCount = 0;
        // 每日订单总数集合
        List<Integer> orderCountList = new ArrayList<>();
        // 每日有效订单集合
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            // 封装参数
            Map<String, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            // 查询每日订单总数
            Integer orderCount = orderMapper.countByMap(map);
            map.put("status", Orders.COMPLETED);
            // 查询每日有效订单数
            Integer validCount = orderMapper.countByMap(map);
            // 加入集合
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
            // 计算总数
            totalOrderCount += orderCount;
            validOrderCount += validCount;
        }
        // 计算有效率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        // 返回结果集
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 查询销量排名TOP10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getOrderNumberTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> top10List = orderMapper.selectOrderTop10(beginTime, endTime);
        List<String> nameList = top10List.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = top10List.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    /**
     * 导出Excel报表接口
     * @param servletResponse
     */
    @Override
    public void exportExcel(HttpServletResponse servletResponse) {
        // 1. 从数据库查询数据
        LocalDate nowDay = LocalDate.now();
        LocalDate beginDay = nowDay.minusDays(30);
        LocalDateTime begin = LocalDateTime.of(beginDay, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(nowDay.minusDays(1), LocalTime.MAX);
        // 获取到30天的营业额数据
        BusinessDataVO businessData = workspaceService.getBusinessData(begin, end);
        // 2. 使用POI将数据动态的写入到Excel模板表格中
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("Template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(is);
            // 获取sheet1 表格页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            // 1.填充时间
            String msg = "时间：" + beginDay + "至" + nowDay;
            sheet.getRow(1).getCell(1).setCellValue(msg);
            // 2.填充概览数据
            sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
            sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());
            // 填充明细数据
            for (int i = 0; i < 30; i++) {
                int row = i + 7;
                LocalDate localDate = nowDay.minusDays(i);
                sheet.getRow(row).getCell(1).setCellValue(localDate.toString());
                LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
                LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
                // 一天的营业额数据
                BusinessDataVO businessDataOneDay = workspaceService.getBusinessData(beginTime, endTime);
                sheet.getRow(row).getCell(2).setCellValue(businessDataOneDay.getTurnover());
                sheet.getRow(row).getCell(3).setCellValue(businessDataOneDay.getValidOrderCount());
                sheet.getRow(row).getCell(4).setCellValue(businessDataOneDay.getOrderCompletionRate());
                sheet.getRow(row).getCell(5).setCellValue(businessDataOneDay.getUnitPrice());
                sheet.getRow(row).getCell(6).setCellValue(businessDataOneDay.getNewUsers());
            }

            // 3. 将填好数据的Excel发送给前端
            ServletOutputStream outputStream = servletResponse.getOutputStream();
            excel.write(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}













